package com.yq.bdm.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.yq.bdm.controller.common.AbstractController;
import com.yq.bdm.service.SysGeneratorService;
import com.yq.bdm.utils.PageUtils;
import com.yq.bdm.utils.ResultMap;

/**
 * 代码生成器
 * 
 * @author shangpan
 * 
 * @date 2016年12月19日 下午9:12:58
 */
@Controller
@RequestMapping("/sysgenerator")
public class SysGeneratorController extends AbstractController {
	@Autowired
	private SysGeneratorService sysGeneratorService;
	
	@RequestMapping("/index.html")
	public String index() {
		return "admin/sysgenerator/sysgenerator.html";
	}

	/**
	 * 
	 * @param searchVal    搜索参数
	 * @param orderDir     排序的顺序asc or desc
	 * @param orderColumn  排序的列名
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/list")
	public ResultMap list(String tableName,String createTime) {
		Map<String, Object> map = new HashMap<>();
		map.put("tableName", tableName);
		map.put("createTime", createTime);
		getPage(map);

		// 查询列表数据
		List<Map<String, Object>> list = sysGeneratorService.queryList(map);
		int total = sysGeneratorService.queryTotal(map);

		PageUtils pageUtil = new PageUtils(list, total, map);

		return ResultMap.ok().put("page", pageUtil);
	}

	/**
	 * 生成代码
	 */
	@RequestMapping("/code")
	public void code(/* String tables, */ HttpServletResponse response) throws IOException {
		String[] tableNames = new String[] {};
		// 获取表名，不进行xss过滤
		String tables = request.getParameter("tables");
		tableNames = JSON.parseArray(tables).toArray(tableNames);

		byte[] data = sysGeneratorService.generatorCode(tableNames);

		response.reset();
		response.setHeader("Content-Disposition",
				"attachment; filename=\"yq-web-sample.zip\"");
		response.addHeader("Content-Length", "" + data.length);
		response.setContentType("application/octet-stream; charset=UTF-8");

		IOUtils.write(data, response.getOutputStream());
	}
}
